package com.yonyou.pmclouds.outter.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.tenant.sdk.UserCenter;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.conf.DeployTypeConfiguration;
import com.yonyou.pmclouds.basecom.conf.PMCloudServerProperties;
import com.yonyou.pmclouds.basecom.conf.YHTSSOLoginProperties;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.HamcUtil;
import com.yonyou.uap.msg.utils.RestAPIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/outter/nc")
public class NCURLenerateController {


    @Autowired
    private YHTSSOLoginProperties yhtSSOLoginProperties;

    @Autowired
    private PMCloudServerProperties pmcloudServerProperties;

//    private String clientId = "HQh24SFOxSh7nxV0eXWB6vGLcNMB8DV3";
//    private String secretKey = "52b874a9-72b9-46f6-b277-b602561e8e52";
//    private String thirdpartLoginUrl = "https://idtest.yyuap.com/cas/thirdpartlogin";

    @GetMapping("/generateURL")
    public Object generateURL(HttpServletRequest request, String urlType, String token) throws BusinessException
    {
        String tantid = request.getHeader("accountId");
        String info;
        if(this.checkEmail(token))
        {
            info = UserCenter.userExistInTenant(tantid,null,token,null);
        }
        else
        {
            info = UserCenter.userExistInTenant(tantid,token,null,null);
        }

        JSONObject object = new JSONObject();
        JSONObject json = JSONObject.parseObject(info);
        if(json!=null)
        {
            if("1".equals(json.getString("status"))&&("1002".equals(json.getString("code"))||"1003".equals(json.getString("code"))))
            {
                String redirectUrl = pmcloudServerProperties.getAddress()+"/outter/nc/redirect?tenantid="+tantid+"&sysid="+ApplicationConsts.APPLICATION_ID+"&token="+token+"&ts="+System.currentTimeMillis()+"&urlType="+urlType;

                String logoutUrl = yhtSSOLoginProperties.getThirdpartLogoutUrl()+"?service=";

                String encodeUrl = "";
                try {
                    encodeUrl = URLEncoder.encode(redirectUrl,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("加签生成失败，请检查配置文件");
                }

                String ts = String.valueOf(new Date().getTime());
                StringBuilder url = new StringBuilder();
                url.append(yhtSSOLoginProperties.getThirdpartLoginUrl());
                url.append("?token=").append(token);
                url.append("&clientId=").append(yhtSSOLoginProperties.getClientId());
                url.append("&ts=").append(ts);
                url.append("&service=").append(encodeUrl);

                Map<String, String> params = new HashMap<>();
                params.put("token",token);
                params.put("clientId",yhtSSOLoginProperties.getClientId());
                params.put("ts",ts);
                params.put("service",redirectUrl);

                String signstr = null;
                try {
                    signstr = URLEncoder.encode(HamcUtil.sign(yhtSSOLoginProperties.getSecretKey(),params),"utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("加签生成失败，请检查配置文件");
                }

                String loginUrl  = RestAPIUtils.encode(url.append("&sign=").append(signstr).toString(),"utf-8");

                try {
                    logoutUrl = logoutUrl + URLEncoder.encode(loginUrl,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("加签生成失败，请检查配置文件");
                }

                object.put("url",loginUrl);
                object.put("logouturl",logoutUrl);
                object.put("tenantid",tantid);
                object.put("sysid", DeployTypeConfiguration.getSysId());
                object.put("token",token);
                return object;
            }
            else
            {
                throw new BusinessException("该用户不存在，请检查关联关系");
            }
        }
        else
        {
            throw new BusinessException("该用户不存在，请检查关联关系");
        }
    }

    private boolean checkEmail(String email) {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
}
